﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RQX.Common.Web.Logger;
using RQX.Common.Web.Logger.ExceptionLogger;
using RQX.Common.Web.Logger.InterfaceLogger;
using RQX.Common.Web.Tools;
using RQX.Common.Web.Web.Container;
using System;

namespace RQX.Common.Web.Web.Filter
{
    /// <summary>
    /// api异常统一处理过滤器
    /// 系统级别异常 500 应用级别异常501
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute, IIoCManager
    {
        private readonly InterfaceLogService _interfaceLogService;
        private readonly ExceptionLogService _exceptionLogService;
        public ApiExceptionFilterAttribute(InterfaceLogService interfaceLogService, ExceptionLogService exceptionLogService)
        {
            _interfaceLogService = interfaceLogService;
            _exceptionLogService = exceptionLogService;
        }

        public override void OnException(ExceptionContext context)
        {
            context.Result = BuildExceptionResult(context.Exception);
            base.OnException(context);
        }

        /// <summary>
        /// 包装处理异常格式
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private JsonResult BuildExceptionResult(Exception ex)
        {
            int code;
            string message;

            string exceptionCode = LoggerFilter.ExceptionLogException(ex, _exceptionLogService);
            bool isApolloException;

            if (ex is ApolloException apolloException)
            {
                code = apolloException.ExceptionType.GetHashCode();
                message = apolloException.Message;
                isApolloException = true;
            }
            else// exception 系统级别异常，不直接明文显示的
            {
                code = 500;
                message = $"系统异常，请联系管理员!异常代码：{exceptionCode}";
                isApolloException = false;
            }

            var apiResponse = new ApiResponse(code, message, null);

            LoggerFilter.ExceptionLogInterface(isApolloException, exceptionCode, apiResponse.ToJson(), _interfaceLogService);

            return new JsonResult(apiResponse);
        }
    }
}
